package com.shutong.edu.invoke.retry.util;

import com.shutong.edu.invoke.retry.handler.RetryJdkProxyHandler;
import com.shutong.edu.invoke.retry.interceptor.RetryCglibInterceptor;
import net.sf.cglib.proxy.Enhancer;

import java.lang.reflect.Proxy;

/**
 *
 * @ClassName: ProxyUtil.java
 * @author: Naughty Guo
 * @date: Jun 2, 2016
 */
public class ProxyUtil {

    /**
     * create jdk proxy instance.
     *
     * @param targetObject
     * @return Object
     * @author Naughty Guo Jun 2, 2016
     */
    public static Object createJdkProxyObject(Object targetObject) {
        Class<?> targetClass = targetObject.getClass();
        Class<?>[] interfaces = targetClass.getInterfaces();
        ClassLoader classLoader = targetClass.getClassLoader();
        RetryJdkProxyHandler retryJdkProxyHandler = new RetryJdkProxyHandler(targetObject);
        return Proxy.newProxyInstance(classLoader, interfaces, retryJdkProxyHandler);

    }

    /**
     * create cglib proxy instance.
     *
     * @param targetObject
     * @return Object
     * @author Naughty Guo Jun 2, 2016
     */
    public static Object createCglibProxyObject(Object targetObject) {
        Class<?> targetClass = targetObject.getClass();
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(targetClass);
        enhancer.setCallback(new RetryCglibInterceptor(targetObject));
        return enhancer.create();
    }
}
